<template>
  <div>
    <div class="article-box">
      <div class="title-box">
        <h2>文章</h2>
      </div>
      <div class="pd-10">
        <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
        <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
        <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
      </div>

      <div class="mg-10">
        <el-button type="primary" @click="handleAdd">新增<i class="el-icon-circle-plus-outline ml-5"></i></el-button>
        <el-popconfirm
            confirm-button-text='是的我确定'
            cancel-button-text='算了在想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="delBatch"
            class="ml-5"
        >
          <el-button type="danger" slot="reference">批量删除<i class="el-icon-remove-outline ml-5"></i></el-button>
        </el-popconfirm>


      </div>

      <el-table
          :data="tableData" border stripe
          :header-cell-style="{ background:'#eee',border: '1px solid #ccc' ,color: '#000'}"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="id" label="id" width="100px">
        </el-table-column>
        <el-table-column prop="name" label="文章标题" width="400">
        </el-table-column>
        <el-table-column prop="content" label="文章内容" width="110">
          <template slot-scope="scope">
            <el-button @click="MdView(scope.row.content)" type="primary">查看文章</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="user" label="发布人" width="150">
        </el-table-column>
        <el-table-column prop="time" label="发布时间" width="200">
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope" >
            <el-button type="primary" @click="selectCourse(scope.row.id)" v-if="user.role === 'ROLE_STUDENT'" >选课<i class="el-icon-edit ml-5"></i></el-button>
            <el-button type="success" @click="handleEdit(scope.row)" v-if="user.role !== 'ROLE_STUDENT'" >编辑<i class="el-icon-edit ml-5"></i></el-button>
            <el-popconfirm
                confirm-button-text='是的我确定'
                cancel-button-text='算了在想想'
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除吗？"
                @confirm="handledelete(scope.row.id)"
                class="ml-5"
            >
              <el-button type="danger" slot="reference" v-if="user.role !== 'ROLE_STUDENT'">删除<i class="el-icon-delete ml-5"></i></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>


      <el-dialog title="文章信息" :visible.sync="dialogFormVisible" width="60%">
        <el-form :model="form"  label-width="80px" size="small">
          <el-form-item label="标题" >
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="内容" >
            <mavon-editor
                ref="md"
                v-model="form.content"
                placeholder="请编辑文章内容"
                :ishljs="true"
                @imgAdd="imgAdd"
            />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="文章信息" :visible.sync="MdViewDialogVis" width="60%">
        <el-card>
          <!-- 预览文章内容 -->
          <mavon-editor
              class="md"
              :value="content"
              :subfield="false"
              :defaultOpen="'preview'"
              :toolbarsFlag="false"
              :editable="false"
              :scrollStyle="true"
              :ishljs="true"
          />
        </el-card>

      </el-dialog>

    </div>

    <div class="article-box-sort">
      <div class="title-box">
        <h2>分类</h2>
      </div>
      <div class="pd-10">
        <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>

        <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
        <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
      </div>

      <div class="mg-10">
        <el-button type="primary" @click="SorthandleAdd">新增<i class="el-icon-circle-plus-outline ml-5"></i></el-button>
        <el-popconfirm
            confirm-button-text='是的我确定'
            cancel-button-text='算了在想想'
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="delBatch"
            class="ml-5"
        >
          <el-button type="danger" slot="reference">批量删除<i class="el-icon-remove-outline ml-5"></i></el-button>
        </el-popconfirm>
      </div>

      <el-table
          :data="sortList" border stripe
          :header-cell-style="{ background:'#eee',border: '1px solid #ccc' ,color: '#000'}"
          @selection-change="SorthandleSelectionChange"
          >
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column type="expand" >
          <template slot-scope="props" v-if="props.row.children!=null">
            <el-table
                :data="props.row.children" border stripe
                @selection-change="handleSelectionChange">
              <el-table-column prop="id" label="id" width="100px">
              </el-table-column>
              <el-table-column prop="name" label="文章标题" width="400">
              </el-table-column>
              <el-table-column prop="content" label="文章内容" width="110">
                <template slot-scope="scope">
                  <el-button @click="MdView(scope.row.content)" type="primary">查看文章</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="user" label="发布人" width="150">
              </el-table-column>
              <el-table-column prop="time" label="发布时间" width="200">
              </el-table-column>

              <el-table-column label="操作">
                <template slot-scope="scope" >
                  <el-popconfirm
                      confirm-button-text='是的我确定'
                      cancel-button-text='算了在想想'
                      icon="el-icon-info"
                      icon-color="red"
                      title="您确定删除吗？"
                      @confirm="deleteSort(scope.row.sortRelevanceId)"
                      class="ml-5"
                  >
                    <el-button type="danger" slot="reference" >删除关联<i class="el-icon-delete ml-5"></i></el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="分类 ID" width="100" >
        </el-table-column>
        <el-table-column prop="name" label="名称" >
        </el-table-column>
        <el-table-column label="封面" align="center" >
          <template slot-scope="scope">
            <el-empty description="分类封面" style="height: 100px" :image="scope.row.coverUrl"></el-empty>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重">
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope" >
<!--            <el-button type="info" @click="handleAdd(scope.row.id)"  v-if="!scope.row.pid && !scope.row.path">新增子菜单<i class="el-icon-plus ml-5"></i></el-button>-->
            <el-button type="info" @click="SortArticleHandleEdit(scope.row.id)" >关联文章<i class="el-icon-plus ml-5"></i></el-button>
            <el-button type="success" @click="SortHandleEdit(scope.row)" >编辑<i class="el-icon-edit ml-5"></i></el-button>
            <el-popconfirm
                confirm-button-text='是的我确定'
                cancel-button-text='算了在想想'
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除吗？"
                @confirm="SortHandledelete(scope.row.id)"
                class="ml-5">
              <el-button type="danger" slot="reference">删除<i class="el-icon-delete ml-5"></i></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="新增分类" :visible.sync="SortdialogFormVisible" width="30%">
        <el-form :model="Sortform"  label-width="80px" size="small">
          <el-form-item label="分类名称" >
            <el-input v-model="Sortform.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="权重" >
            <el-input v-model="Sortform.weight" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="分类展示图片" >
            <el-upload
                :action=" serverIp +'/files/upload'"
                :limit="1"
                :on-success="handleAvatarSuccess"
                list-type="picture-card"
                ref="uploadImg"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="form.coverImg" alt="">
            </el-dialog>

          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="Sortsave">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="关联文章" :visible.sync="SortArticledialogFormVisible" width="30%">
        <el-select v-model="SelectArtcle"  multiple clearable placeholder="请选择" style="width: 100%">
          <el-option v-for="item in NoSortArticleList" :key="item.id" :label="item.name" :value="item.id">
             {{item.name}}
          </el-option>
        </el-select>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="SortArticle">确 定</el-button>
        </div>
      </el-dialog>
    </div>



  </div>
</template>

<script>



import axios from "axios";

export default {
  name: "Article",
  data(){
    return{
      tableData: [], //分页数据
      sortList: [],
      total: 0, //总条数
      pageNum: 0,
      pageSize: 5,
      form: {}, //表格数据
      Sortform: {}, //分类表格数据
      name: "", //查询
      multipleSelection: [], //多选删除
      SortmultipleSelection: [], //分类多选删除
      dialogFormVisible: false, //新增按钮
      SortdialogFormVisible: false, //分类新增按钮
      SortArticledialogFormVisible: false, //关联文章
      dialogVisible: false,
      SelectArtcle:[],
      NoSortArticleList: [], //未关联文章
      CurrentSelectSortId: 0,
      teachers: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")):{},
      content: '',  //文章内容
      MdViewDialogVis: false //文章显示
    }
  },
  created() {
    this.load();
    this.SortLoad();
  },
  methods:{
    //显示md文档
    MdView(content){
      this.content = content;
      this.MdViewDialogVis = true
    },
    selectCourse(courseId){
        this.request.post("/course/studentCourse",{
            studentId: this.user.id,
            courseId: courseId
        }).then(res=>{
          if(res.code === "200"){
            this.$message.success("添加成功")
          }else {
            this.$message.error(res.msg)
          }
        })
    },
    //分页请求
    load(){
      this.request.get("/article/page",{
        params:{
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res =>{
        if(res.code === "200"){
          this.tableData = res.data.data
          this.total = res.data.total
        }else {
          this.$message.error(res.msg)
        }
      })

      //查询字段为
      this.request.get("/user/role/ROLE_TEACHER").then(res =>{
        if(res.code === "200"){
          this.teachers = res.data
        }else {
          this.$message.error(res.msg)
        }
      })

    },
    SortLoad(){
      this.request.get("/articleSort").then(res =>{
        if(res.code === "200"){
          this.sortList = res.data;
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //分页方法
    handleSizeChange(pageSize) {
      this.pageSize=pageSize;
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load()
    },
    //重置搜索框
    reset(){
      this.name = "";
      this.load()
    },
    //新增按钮
    handleAdd(){
      this.dialogFormVisible = true;
      this.form = {}
    },
    SorthandleAdd(){
      this.SortdialogFormVisible = true;
      this.Sortform = {}
    },
    //编辑按钮
    handleEdit(row){
      this.form = row
      this.dialogFormVisible = true
    },
    SortHandleEdit(row){
      this.Sortform = row
      this.SortdialogFormVisible = true
    },
    SortArticleHandleEdit(id){
      this.CurrentSelectSortId = id;
      this.request.get("/articleSort/NoSortArticle/"+id, this.form).then(res=>{

        if(res.code ==="200"){
          this.NoSortArticleList = res.data;
          this.SortArticledialogFormVisible = true;
        }else {
          this.$message.error(res.msg)
        }

      })
    },
    //确定新增
    save(){
      this.request.post("/article", this.form).then(res=>{

        if(res.code ==="200"){
          this.$message.success(res.data)
          this.form ={}
          this.dialogFormVisible = false;
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    Sortsave(){
      this.request.post("/articleSort", this.Sortform).then(res=>{

        if(res.code ==="200"){
          this.$message.success(res.data)
          this.Sortform ={}
          this.SortdialogFormVisible = false;
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //新增关联
    SortArticle(){
      //SelectSortArtcle
      for (var item of this.SelectArtcle) {
        item = parseInt(item);
      }
      this.request.post("/articleRelevanceSort/SelectSortArtcle/"+this.CurrentSelectSortId,this.SelectArtcle).then(res=>{

        if(res.code ==="200"){
          this.$message.success(res.date)
          this.SortLoad()
          this.cancel();
          this.SelectArtcle = [];
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //取消按钮
    cancel() {
      this.dialogFormVisible=false
      this.SortdialogFormVisible=false
      this.SortArticledialogFormVisible=false;
      this.SelectArtcle = [];
      this.load()
    },

    //删除按钮
    handledelete(id){
      // console.log("关联",id)
      this.request.delete("/article/"+id).then(res=>{
        if(res.code === "200"){
          this.$message.success(res.data)
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //删除关联
    deleteSort(id){
      console.log(id)
      this.request.delete("/articleRelevanceSort/"+id).then(res=>{
        if(res.code === "200"){
          this.$message.success(res.data)
          this.SortLoad()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    SortHandledelete(id){

      this.request.delete("/articleSort/"+id).then(res=>{
        if(res.code === "200"){
          this.$message.success(res.data)
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //批量删除多选
    handleSelectionChange(val){

      this.multipleSelection  = val
    },
    SorthandleSelectionChange(val){

      this.SortmultipleSelection  = val
    },
    //点击批量删除
    delBatch(){
      let ids= this.multipleSelection.map(v => v.id)  //将数组内的id提取出来
      this.request.delete("/article/del/batch",{
        data: ids
      }).then(res=>{
        if(res.code === "200"){
          this.$message.success(res.data)
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //导入成功的回调
    handleFileUploadSuccess(res){
      this.load();
      this.$message.success("上传成功")
    },
    //下载连接
    download(url){
      window.open(url);
    },
    changeEnable(row){
      row.enable = row.enable ===1? 0: 1;
      this.request.post("/article",row).then(res=>{
          if (res.code === "200"){
            this.$message.success("操作成功")
          } else {
            this.$message.error("操作失败")
          }
      })
    },
    // 绑定@imgAdd event
    imgAdd(pos, $file) {

      let $vm = this.$refs.md
      // 第一步.将图片上传到服务器.
      const formdata = new FormData();
      formdata.append('file', $file);
      let s = JSON.stringify(formdata);
      // axios("http://localhost:8089/files/upload",{
      this.request({
        method: 'post',
        url:`/files/upload`,
        data: formdata,
        headers: {'Content-Type': 'multipart/form-data'}
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        $vm.$img2Url(pos, res.data);
      })
    },
    //图片上传方法
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.Sortform.coverUrl = res.data;
    },
    handlePictureCardPreview(file) {
      // this.form.goodsImgUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
    },

  }
}
</script>

<style lang="less" scoped>
h2{
  font-weight: 800;
  font-size: 30px;
}
.article-box{

}
</style>